# Build script for the single-purpose initramfs (Live CD).
#
# Copyright (c) 2017-2018 Matias Fonzo, <selk@dragora.org>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

mkdir -p -- "${rootdir}/initrd"
cd -- "${rootdir}/initrd"

# Create essential directories for the image

mkdir -p -m 755 dev proc sys .UP

cat << "EOF" > init
#! /bin/busybox ash

/bin/busybox mount -n -o nosuid,noexec,nodev -t proc proc /proc
/bin/busybox mount -n -o nosuid,noexec,nodev -t sysfs sysfs /sys
/bin/busybox mount -n -t devtmpfs devtmpfs /dev

/bin/busybox sleep 2

/bin/busybox mount -n -o rw,size=100% -t tmpfs tmpfs /.UP
/bin/busybox mkdir /.UP/cdrom /.UP/squash /.UP/rw /.UP/work /.UP/union

# Mount ISO and system image
/bin/busybox mount -n -t iso9660 LABEL=Dragora /.UP/cdrom
/bin/busybox mount -n -o loop -t squashfs /.UP/cdrom/dragora.sfs /.UP/squash

# Merge Squashfs with OverlayFS
/bin/busybox mount -n \
 -o lowerdir=/.UP/squash,upperdir=/.UP/rw,workdir=/.UP/work \
 -t overlay overlay /.UP/union

# Move virtual file systems prior to switch_root
/bin/busybox mount --move /dev   /.UP/union/dev
/bin/busybox mount --move /proc  /.UP/union/proc
/bin/busybox mount --move /sys   /.UP/union/sys

exec /bin/busybox switch_root /.UP/union /sbin/init

EOF

chmod 750 ./init

# Make initramfs

rm -f ./initrd.img
find . | sed 's!^./!!' | cpio -oC512 -H newc | \
 lzip -s16 -0c > initrd.img

